<?php
/* ========================================
 * --------------------
 *  Criteria.php
 * --------------------
 * Created on 30.03.2010
 * ========================================
 * $Revision: $
 * $Author: Dmitry Boycov
 * $HeadURL: $
 * $Id: $
 * ========================================
 * Changes ["date: description (who)"]:
 *
 * 30.03.2010: Original version (WHo)
 * 15:19:50: Time
 */

class Criteria {

	// operators
	public static $IN = "IN";
	public static $EQUAL = "=";
	//
	private $field = null;
	private $value = null;
	private $operator = null;
	private $andCriteria = null;
	private $orCriteria = null;

	public function _construct($field = null,$operator = null,$value = null){
		if(!is_null($field) && !is_null($value) && !is_null($operator)){
			$this->field = $field;
			$this->operator = $operator;
			$this->value = $value;
		}
	}

	public function addAnd($criteria){
		if($criteria instanceof Criteria){
			if(is_null($this->andCriteria)){
				$this->andCriteria = array();
			}
			array_push($this->andCriteria,$criteria);
		}
	}

	public function addOr($criteria){
		if($criteria instanceof Criteria){
			if(is_null($this->orCriteria)){
				$this->andCriteria = array();
			}
			array_push($this->orCriteria,$criteria);
		}
	}

	protected function escape($string) {
		if(get_magic_quotes_runtime()) $string = stripslashes($string);
		return mysql_real_escape_string($string);
	}

	/**
	 * generate "where" sting
	 * @return string
	 */
	public function generate(){
		if(is_null($this->field) && is_null($this->andCriteria) && is_null($this->orCriteria)) return "";
		$str = "";
		if(!is_null($this->field) && !is_null($value) && !is_null($this->operator)){
			if($this->operator == self::$IN){
				// todo
			}else{
				$str = $this->field.$this->operator.$this->escape($this->value);
			}
		}
		//////
		if(!is_null($this->andCriteria)){
			$buf = array();
			foreach($this->andCriteria as $k=>$v){
				$and = $v->generate();
				if($and!="" && !is_null($and)){
					array_push($buf,"(".$and.")");
				}
			}
			$and = join(" AND ",$buf);
			if($str!="" && !is_null($str)){
				$str.=" AND (".$and.")";
			}else{
				$str = $and;
			}
		}
		//////
		if(!is_null($this->orCriteria)){
			$buf = array();
			foreach($this->orCriteria as $k=>$v){
				$or = $v->generate();
				if($or!="" && !is_null($or)){
					array_push($buf,"(".$or.")");
				}
			}
			$or = join(" OR ",$or);
			if($str!="" && !is_null($str)){
				$str.=" AND (".$or.")";
			}else{
				$str = $or;
			}
		}
		
		return $str;
	}

}
?>